package com.yyfax.pay.common.filter;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Multimap;
import com.yyfax.framework.filter.CacheHttpServletRequestWrapper;
import com.yyfax.framework.filter.YYFilter;

public class MockFilter extends YYFilter{
	
	@Resource
	private MockConfigure configure;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		if(configure.isMock() && request instanceof CacheHttpServletRequestWrapper){
			CacheHttpServletRequestWrapper req = (CacheHttpServletRequestWrapper)request;
			String uri = request.getRequestURI();
			for(String mockURI : configure.getConfigures().keys()){
				if(Pattern.matches(mockURI, uri)){
					Collection<MockConfigure> collection = configure.getConfigures().get(uri);
					for(MockConfigure mock : collection){
						if(Pattern.matches(mock.getReg(), req.getBodyContent())){
							OutputStream out = response.getOutputStream();
							out.write(mock.getResponse().getBytes());
							out.flush();
							return ;
						}
					}
				}
			}
		}
	    filterChain.doFilter(request, response);
	}
}
